package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;
    @RequestMapping("/list")
    @RequirePermission(name = "权限查询",expression = "permission:list")
    public String list(Model model, QueryObject qo){
        PageResult<Permission> pageResult = permissionService.query(qo);
        List<Permission> permissions = permissionService.listAll();
        /*for (Permission permission : permissions) {
            permission.getId();
            permission.getName();
            permission.getSn();
        }*/


        System.out.println(pageResult);
        model.addAttribute("pageResult",pageResult);
        return "permission/list";
    }



    @RequestMapping("/delete")
    @ResponseBody
    @RequirePermission(name = "权限删除",expression = "permission:delete")
    public JsonResult delete(Long id){
        try {
            permissionService.delete(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("删除失败",false);
        }

    }




    @RequestMapping("/input")
    @RequirePermission(name = "权限添加",expression = "permission:input")
    public String input(Long id,Model model){
        if(id!=null){
            Permission permission = permissionService.get(id);
            model.addAttribute("permission",permission );
        }
        return "permission/input";
    }
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Permission permission){
        if (permission.getId()==null){
            permissionService.save(permission);
        }else{
            permissionService.update(permission);
        }
        return "redirect:/permission/list.do";
    }




    @RequestMapping("/reload")
    @ResponseBody
    @RequirePermission(name = "权限重载",expression = "permission:reload")
    public JsonResult reload(Model model){

        try {
            permissionService.reload();
            return new JsonResult("权限加载成功",true);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult("权限加载失败",false);
        }

    }

}
